package com.zhihuichongcheng.application.ui.approval.fragment;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.smartlib.cmnObject.recycleView.OnItemOnclick;
import com.smartlib.cmnObject.util.DeviceUtil;
import com.smartlib.cmnObject.util.DialogUtil;
import com.smartlib.cmnObject.util.GsonUtil;
import com.smartlib.cmnObject.util.ToastOpt;
import com.yunkeshuzhi.common.module.SSModule;
import com.yunkeshuzhi.common.utils.DateUtils;
import com.yunkeshuzhi.common.utils.SSUtils;
import com.yunkeshuzhi.uikit.views.dd.DDListMenuAdapter;
import com.yunkeshuzhi.uikit.views.dd.SSDateIntervalDDMenu;
import com.yunkeshuzhi.uikit.views.dd.SSListDDMenu;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseFragment;
import com.zhihuichongcheng.application.bean.approval.ApprovalBean;
import com.zhihuichongcheng.application.bean.approval.ApprovalCategory;
import com.zhihuichongcheng.application.bean.approval.ApprovalWaitBean;
import com.zhihuichongcheng.application.constant.NetworkAPI;
import com.zhihuichongcheng.application.net.HttpCallback;
import com.zhihuichongcheng.application.ss.module.ApprovalModule;
import com.zhihuichongcheng.application.ss.module.TypeModule;
import com.zhihuichongcheng.application.ui.approval.activity.ApprovalDetailActivity;
import com.zhihuichongcheng.application.ui.approval.adapter.WaittingApprovalAdapter;
import com.zhihuichongcheng.application.util.CollectionUtils;
import com.zhihuichongcheng.application.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by 3water on 2016/11/10.
 */

public class WaittingApprovalFragment extends BaseFragment {
    public static final int REQUEST_WAITING_APPROVAL_DETAIL = 44413;
    private List<ApprovalWaitBean> mListData = new ArrayList<>();
    private XRecyclerView mRcvApproval;
    private WaittingApprovalAdapter mAdapter = null;
    private int mPageSize = 10;
    private int mPage = 1;
    private LinearLayout mLlNoData;

    private SSListDDMenu mApprovalTypeMenu;
    private SSListDDMenu mApprovalMenu;
    private SSDateIntervalDDMenu mDateStartMenu;

    private List<ApprovalCategory> mApprovalCategories = new ArrayList<>();
    private List<ApprovalBean> mApprovalBeans = new ArrayList<>();
    private int index = 0;
    private TypeModule mCurrentSelectType;
    private ApprovalModule mCurrentSelectApproval;
    private String startTime;
    private String endTime;
    //搜索相关
    private LinearLayout mSearchLayout;
    private TextView mBtnSearch;
    private EditText mInputSearch;
    private ImageView mBtnSearchClear;

    @Override
    protected void init() {
        super.init();
        initView();
        requestFormCategoriesList();
        DialogUtil.showLoadDiadlog(mContext);
        initData(mPage);
    }

    private void initView() {
        mRcvApproval = (XRecyclerView) mView.findViewById(R.id.rcv_approvalList);
        mRcvApproval.setLayoutManager(new LinearLayoutManager(mContext));

        mApprovalTypeMenu = (SSListDDMenu) mView.findViewById(R.id.dd_menu_approval_type);
        mApprovalTypeMenu.setSelectType(DDListMenuAdapter.SelectType.Radio);

        mApprovalMenu = (SSListDDMenu) mView.findViewById(R.id.dd_menu_approval);
        mApprovalMenu.setSelectType(DDListMenuAdapter.SelectType.Radio);
        mDateStartMenu = (SSDateIntervalDDMenu) mView.findViewById(R.id.dd_menu_date);

        mSearchLayout = (LinearLayout) mView.findViewById(R.id.search_layout);
        mBtnSearch = (TextView) mSearchLayout.findViewById(R.id.btn_search);
        mBtnSearchClear = (ImageView) mSearchLayout.findViewById(R.id.im_del);
        mInputSearch = (EditText) mSearchLayout.findViewById(R.id.et_search);

        mAdapter = new WaittingApprovalAdapter(mContext);
        mAdapter.setOnItemOnclick(new OnItemOnclick<ApprovalWaitBean>() {
            @Override
            public void onClick(ApprovalWaitBean approvalBean, int position) {
                Intent intent = new Intent(getContext(), ApprovalDetailActivity.class);
                intent.putExtra("userFormInstanceId", approvalBean.getUserFormInstanceId());
                intent.putExtra("taskId", approvalBean.getTaskId());
                getActivity().startActivityForResult(intent, REQUEST_WAITING_APPROVAL_DETAIL);
            }
        });
        mLlNoData = (LinearLayout) mView.findViewById(R.id.ll_nodata);
        mRcvApproval.setAdapter(mAdapter);
        mRcvApproval.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                refresh();
            }

            @Override
            public void onLoadMore() {
                mPage++;
                initData(mPage);
            }
        });


        mApprovalMenu.setOnCommitListener(new SSListDDMenu.OnCommitListener() {
            @Override
            public void onClick(List<SSModule> list) {
                if (!SSUtils.isEmpty(list)) {
                    mCurrentSelectApproval = (ApprovalModule) list.get(0);
                } else {
                    mCurrentSelectApproval = null;
                }
                refresh();
            }

            @Override
            public void onReset() {
                mCurrentSelectApproval = null;
                refresh();
            }
        });
        mApprovalTypeMenu.setOnCommitListener(new SSListDDMenu.OnCommitListener() {
            @Override
            public void onClick(List<SSModule> list) {
                if (!SSUtils.isEmpty(list)) {
                    mCurrentSelectType = (TypeModule) list.get(0);
                } else {
                    mCurrentSelectType = null;
                }
                setApprovalMenu();
                refresh();
            }

            @Override
            public void onReset() {
                mCurrentSelectType = null;
                setApprovalMenu();
                refresh();
            }
        });
        mDateStartMenu.setOnCommitListener(new SSDateIntervalDDMenu.IOnCommitListener() {
            @Override
            public void onCommit(Date date, Date date1) {
                startTime = DateUtils.formatDate(date);
                endTime = DateUtils.formatDate(date1);
                refresh();
            }

            @Override
            public void onReset() {
                startTime = null;
                endTime = null;
                refresh();
            }
        });

        mInputSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!SSUtils.isEmpty(s) && !SSUtils.isEmpty(s.toString())) {
                    mBtnSearchClear.setVisibility(s.toString().length() == 0 ? View.GONE : View.VISIBLE);
                } else {
                    mBtnSearchClear.setVisibility(View.GONE);
                }
            }
        });
        mBtnSearchClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mInputSearch.setText("");
            }
        });
        mBtnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refresh();
            }
        });
    }

    private void requestFormCategoriesList() {
        HashMap<String, String> param = new HashMap<>();
        param.put("token", mUser.getToken());
        manager.post(NetworkAPI.Approval_Category, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                mApprovalCategories.clear();
                mApprovalCategories.addAll(GsonUtil.paraeFromStringToList(value, ApprovalCategory.class));
                if (mApprovalCategories.size() > 0) {
                    for (int i = 0; i < mApprovalCategories.size(); i++) {
                        requestFormList(mApprovalCategories.get(i).getUserFormCategoryId());
                    }
                }
            }

            @Override
            public void onFailure(String value) {
                ToastOpt.createToast(getContext(), "请求失败 ");
            }
        }, param);
    }

    private void initData(final int page) {

        HashMap<String, String> param = new HashMap<>();
        param.put("token", mUser.getToken());
        param.put("pageRows", "" + mPageSize);
        param.put("curPage", "" + page);
        if (!SSUtils.isEmpty(startTime))
            param.put("startDate", startTime);
        if (!SSUtils.isEmpty(endTime))
            param.put("endDate", endTime);
        if (!SSUtils.isEmpty(mCurrentSelectType))
            param.put("userFormCategoryId", mCurrentSelectType.getApprovalCategory().getUserFormCategoryId());
        if (!SSUtils.isEmpty(mCurrentSelectApproval))
            param.put("userFormInfoId", mCurrentSelectApproval.getApprovalBean().getUserFormInfoId());
        if (!SSUtils.isEmpty(mInputSearch))
            param.put("searchContent", mInputSearch.getText().toString().trim());

        manager.post(NetworkAPI.Approval_wait, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {

                mListData = GsonUtil.paraeFromStringToList(value, ApprovalWaitBean.class);
                if (page == 1) {
                    mAdapter.clear();
                    if (mListData.size() == 0) {
                        mLlNoData.setVisibility(View.VISIBLE);
                        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mLlNoData.getLayoutParams();
                        params.setMargins(0, (DeviceUtil.getHeight(mContext) - DeviceUtil.dip2px(mContext, 50)) / 10 * 4 - DeviceUtil.dip2px(mContext, 75), 0, 0);
                        mLlNoData.setLayoutParams(params);
                        mRcvApproval.setVisibility(View.GONE);
                    } else {
                        mLlNoData.setVisibility(View.GONE);
                        mRcvApproval.setVisibility(View.VISIBLE);
                    }
                }
                mAdapter.setdata(mListData);
                mAdapter.notifyDataSetChanged();
                mRcvApproval.loadMoreComplete();
                mRcvApproval.refreshComplete();
                if (mListData.size() < mPageSize) {
                    mRcvApproval.setNoMore(true);
                }
                DialogUtil.dismiss(mContext);
            }

            @Override
            public void onFailure(String value) {
                DialogUtil.dismiss(mContext);
                if (page == 1) {
                    mLlNoData.setVisibility(View.VISIBLE);
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mLlNoData.getLayoutParams();
                    params.setMargins(0, (DeviceUtil.getHeight(mContext) - DeviceUtil.dip2px(mContext, 50)) / 10 * 4 - DeviceUtil.dip2px(mContext, 75), 0, 0);
                    mLlNoData.setLayoutParams(params);
                    mRcvApproval.setVisibility(View.GONE);
                }
            }
        }, param);

    }

    private void refresh() {
        mPage = 1;
        DialogUtil.showLoadDiadlog(getContext());
        initData(mPage);
        refreshSearchLayout();
    }

    private void setApprovalMenu() {
        final List<SSModule> modules = new ArrayList<>();
        CollectionUtils.iterator(mApprovalBeans, new CollectionUtils.AIIteratorListCallBack() {
            @Override
            public boolean callback(Object data, int position) {
                ApprovalBean item = (ApprovalBean) data;
                if (!SSUtils.isEmpty(mCurrentSelectType)) {
                    if (mCurrentSelectType.getApprovalCategory().getUserFormCategoryId().
                            equals(item.getUserFormCategory().getUserFormCategoryId())) {
                        modules.add(new ApprovalModule(item));
                    }
                } else {
                    modules.add(new ApprovalModule(item));
                }
                return false;
            }
        });
        mApprovalMenu.resetActions(modules);
    }

    private void requestFormList(String userFormCategoryId) {
        HashMap<String, String> param = new HashMap<>();
        param.put("userFormCategoryId", userFormCategoryId);
        param.put("token", mUser.getToken());
        manager.post(NetworkAPI.Approval_List, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                if (!StringUtils.isEmpty(value))
                    mApprovalBeans.addAll(GsonUtil.paraeFromStringToList(value, ApprovalBean.class));
                index++;
                if (index == mApprovalCategories.size()) {
                    index = 0;
                    setDDMenu();
                }
            }

            @Override
            public void onFailure(String value) {
                ToastOpt.createToast(getContext(), "请求失败 ");
            }
        }, param);
    }

    private void refreshSearchLayout() {
        if (!SSUtils.isEmpty(mCurrentSelectApproval) && !SSUtils.isEmpty(mCurrentSelectType))
            mSearchLayout.setVisibility(View.VISIBLE);
        else
            mSearchLayout.setVisibility(View.GONE);
    }

    private void setDDMenu() {
        setTypeMenu();
        setApprovalMenu();
    }

    private void setTypeMenu() {
        final List<SSModule> modules = new ArrayList<>();
        CollectionUtils.iterator(mApprovalCategories, new CollectionUtils.AIIteratorListCallBack() {
            @Override
            public boolean callback(Object data, int position) {
                modules.add(new TypeModule((ApprovalCategory) data));
                return false;
            }
        });
        mApprovalTypeMenu.setActions(modules);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_approval_list;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            refresh();
        }
    }
}
